package user

import (
	"net/http"
	"regexp"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

func ToRegister(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "user/register.html", nil)
}

func DoRegister(ctx *gin.Context) {

	// 获取前端数据
	UserName := ctx.PostForm("user_name")
	Password := ctx.PostForm("pwd")
	Cpassword := ctx.PostForm("cpwd")
	Email := ctx.PostForm("email")
	Allow := ctx.PostForm("allow")

	// 校验数据
	if UserName == "" || len(UserName) < 4 || len(UserName) > 20 {
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "用户名格式错误"})
		return
	}

	if Password == "" || len(Password) < 8 || len(Password) > 20 {
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "密码格式错误"})
		return
	}

	if Password != Cpassword {
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "两次密码不一致"})
		return
	}

	reg, _ := regexp.Compile("^[a-z0-9][\\w.\\-]*@[a-z0-9\\-]+(\\.[a-z]{2,5}){1,2}$")
	email := reg.FindString(Email)
	if email == "" {
		global.App.Log.Sugar().Errorf("%s: 用户注册邮箱格式解析异常", UserName)
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "邮箱格式错误"})
		return
	}

	if Allow != "on" {
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "请同意勾选“天天生鲜用户使用协议”"})
		return
	}

	// 验证用户是否存在
	if ret := global.App.DB.Where("name = ?", UserName).Find(&model.User{}); ret.RowsAffected != 0 {
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "注册用户已存在"})
		return
	}

	ret := global.App.DB.Create(&model.User{
		Name:     UserName,
		Password: utils.EncryPwd(Password),
		Email:    email,
	})
	if ret.RowsAffected == 0 {
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "用户注册失败"})
		return
	}

	// 生成token,发送激活邮件
	token, err := utils.GenerateToken(UserName, email, global.App.Config.Jwt.AccessSecret, global.App.Config.Jwt.AccessExpire)
	if err != nil {
		global.App.Log.Error(err.Error())
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "后台发生错误"})
		return
	}
	if ok, err := utils.ActiveEmail(UserName, email, global.App.Config.App.AppName, global.App.Config.App.APPUrl, global.App.Config.App.AppPort, token); !ok {
		global.App.Log.Error(err.Error())
		ctx.HTML(http.StatusOK, "user/register.html", map[string]string{"errMsg": "发送激活邮件失败"})
		return
	}

	// 激活成功，跳转首页
	global.App.Log.Sugar().Infof("用户注册成功:[%s,%s,%s]", UserName, Password, Email)
	ctx.Redirect(http.StatusFound, "/ttsx/index")
}
